package com.example.fragmentdemo.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.webkit.MimeTypeMap;

import androidx.core.content.FileProvider;

import com.example.fragmentdemo.constant.Constant;

import java.io.File;

public class ShareUtils {

    public static void share(Activity activity, String path) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);

        // 根据文件后缀名获取MIME类型
        String mimeType = getMimeType(path);
        shareIntent.setType(mimeType);

        File file = new File(path);
        try {
            // 注意：这里的context应该是调用该方法的Activity或者其他Context对象
            Uri contentUri = FileProvider.getUriForFile(activity, Constant.AUTHORITY, file);
            shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            // 启动分享选择器
            activity.startActivity(Intent.createChooser(shareIntent, "Choose an app to share"));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            // 处理错误情况，比如FileProvider配置错误导致的异常
        }
    }

    private static String getMimeType(String path) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(path);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
        }
        return type != null ? type : "application/octet-stream"; // 默认使用二进制流类型
    }
}